using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;

using Elephant.Utility;

using Elephant.Framework;
using Elephant.Framework.Services;

namespace Elephant.Utility.Components
{
    // todo: implement control scheme
    [ComponentDependency(typeof(FreeLookCamera))]
    public sealed class FreeLookCameraController : EntityComponent
    {
        FreeLookCamera cam;

        Vector2 offMousePos, preMousePos;

        public override void Initialize(bool addDependencies)
        {
            base.Initialize(addDependencies);

            cam = Owner.Find<FreeLookCamera>();
        }

        public override void Update(GameTime gameTime)
        {
            MouseState ms = Mouse.GetState();
            KeyboardState ks = Keyboard.GetState();

            if (ms.MiddleButton == ButtonState.Pressed) {
                cam.Rotate(offMousePos.X * 0.005f, offMousePos.Y * 0.005f, 0);
            }

            if (ks.IsKeyDown(Keys.W)) {
                cam.Translate(new Vector3(0, 0, -1) * (cam.Speed * (float)gameTime.ElapsedGameTime.TotalSeconds));
            }
            if (ks.IsKeyDown(Keys.S)) {
                cam.Translate(new Vector3(0, 0, 1) * (cam.Speed * (float)gameTime.ElapsedGameTime.TotalSeconds));
            }
            if (ks.IsKeyDown(Keys.A)) {
                cam.Translate(new Vector3(-1, 0, 0) * (cam.Speed * (float)gameTime.ElapsedGameTime.TotalSeconds));
            }
            if (ks.IsKeyDown(Keys.D)) {
                cam.Translate(new Vector3(1, 0, 0) * (cam.Speed * (float)gameTime.ElapsedGameTime.TotalSeconds));
            }

            // Save the offset between mousecoordinates, and the current mouse pos
            offMousePos = preMousePos - new Vector2(ms.X, ms.Y);
            preMousePos = new Vector2(ms.X, ms.Y);
        }
    }
}
